from docx import Document
import os
from docx.shared import Pt, Inches
import pandas as pd
import xlwings as xw
from PIL import ImageGrab


def gen_doc(frequency, begin_date, x_name, y_name):
    doc = Document()

    for result_label in ["annualized_return", "annualized_volatility", "annualized_shape", "turnover", "margin",
                         "fitness", "excess_return", "relative_return", "max_drawdown", "information_ratio",
                         "calmar_ratio", "yearly_count", "winning_rate", "profit_loss_ratio", "kelly_fraction"]:
        doc.add_heading(f'{result_label}的热力图')
        doc.add_picture(f'{frequency}/{begin_date}/heatmap_png/{result_label}.png', width=Inches(7))


    for table_name in ["annualized_shape", "margin", "calmar_ratio", "information_ratio", "kelly_fraction"]:
        path = f"{frequency}/{begin_date}/top3/{table_name}.csv"
        table_df = pd.read_csv(path)
        app = xw.App(visible=True, add_book=False)
        app.display_alerts = False
        app.screen_updating = True
        wb = app.books.open(path)
        sht = wb.sheets[0]
        pic_range = sht.used_range
        pic_range.autofit()
        pic_range.copy()
        while True:
            try:
                img = ImageGrab.grabclipboard()
                table_png = f"{frequency}/{begin_date}/top3/{table_name}.png"
                img.save(table_png)
                break
            except Exception as e:
                print(e)
        wb.close()
        app.quit()
        doc.add_heading(f'{table_name}表现最好和最差的3组参数')
        doc.add_picture(table_png, width=Inches(7))
        for _, row in table_df.iterrows():
            oi_l = int(row[f'{x_name}'])
            oi_s = int(row[f'{y_name}'])
            doc.add_heading(f'{x_name}={oi_l},{y_name}={oi_s}的折线图')
            doc.add_picture(f"{frequency}/{begin_date}/png/{x_name}={oi_l},{y_name}={oi_s}.png", width=Inches(7))

    doc.save(f'{frequency}/{begin_date}/{frequency}_{begin_date}.docx')
    print("带表格的文档创建完成!")